<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="物料类别"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button
          type="primary"
          v-auth="'materialtype_add'"
          :icon="CirclePlus"
          @click="openAddEdit('新增分类', { status: 1017001, category_code: `WLFL${getTimestamp()}`, sort: 20 })"
        >
          新增
        </el-button>
        <el-button
          v-auth="'materialtype_del'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          :active-value="1017001"
          :inactive-value="1017002"
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          :active-action-icon="Check"
          :inactive-action-icon="Close"
          :loading="switchLoading"
          :before-change="() => changeDataScope(scope.row)"
        />
      </template>
      <template #operation="{ row }">
        <el-button
          type="primary"
          v-auth="'materialtype_add'"
          link
          :icon="CirclePlus"
          @click="
            openAddEdit(`新增子分类【${row.category_name}】`, {
              status: 1017001,
              parent_id: row.id,
              category_code: `WLFL${getTimestamp()}`,
              sort: 20
            })
          "
        >
          新增子分类
        </el-button>
        <el-button
          v-auth="'materialtype_batchadd'"
          type="primary"
          link
          :icon="Edit"
          @click="bachAdd(`批量新增-父级【${row.category_name}】`, row)"
        >
          批量新增子分类
        </el-button>
        <el-button v-auth="'materialtype_edit'" type="primary" link :icon="EditPen" @click="openAddEdit('编辑分类', row, false)">
          编辑
        </el-button>
        <el-button v-auth="'materialtype_del'" type="primary" link :icon="Delete" @click="deleteInfo(row)"> 删除 </el-button>
      </template>
    </ProTable>
    <MaterialTypeForm ref="materialTypeFormRef" />
    <BatchAddTable ref="batchAddTableRef" />
  </div>
</template>
<script setup>
defineOptions({
  name: 'BasicMaterialType'
});
import { h, ref } from 'vue';
import { CirclePlus, Delete, EditPen, Edit, Close, Check } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import { useHandleData } from '@/hooks/useHandleData';
import {
  getMaterialTypeList,
  deleteMaterialType,
  updateMaterialTypeStatus,
  createMaterialType,
  updateMaterialType,
  batchCreateMaterialType
} from '@/api/modules/basicinfo/material_type';
import MaterialTypeForm from './materialTypeForm.vue';
import BatchAddTable from './batchAddTable.vue';
import { useOptionsStore } from '@/stores/modules/options';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTimestamp } from '@/utils/index';
const optionsStore = useOptionsStore();
const batchAddTableRef = ref();
const materialTypeFormRef = ref();
const proTableRef = ref();
const switchLoading = ref(false);
// 表格配置项
const columns = [
  { type: 'selection', width: 80 },
  { prop: 'category_code', label: '编码' },
  { prop: 'category_name', label: '名称' },
  { prop: 'sort', label: '排序' },
  { prop: 'remark', label: '备注' },
  {
    prop: 'status',
    label: '状态'
  },
  { prop: 'operation', label: '操作', width: 400, fixed: 'right' }
];
// 搜索条件项
const searchColumns = [
  { prop: 'category_name', label: '名称', el: 'input' },
  { prop: 'category_code', label: '编码', el: 'input' }
];
// 获取table列表
const getTableList = params => {
  return getMaterialTypeList(params);
};
// 打开 drawer(新增、查看、编辑)
const openAddEdit = async (title, row = {}, isAdd = true) => {
  const params = {
    title,
    row: { ...row },
    api: isAdd ? createMaterialType : updateMaterialType,
    getTableList: proTableRef.value?.getTableList,
    isAdd
  };
  materialTypeFormRef.value?.acceptParams(params);
};

// 批量新增
const bachAdd = async (title, row = {}) => {
  const params = {
    title,
    row: { ...row },
    api: batchCreateMaterialType,
    getTableList: proTableRef.value?.getTableList
  };
  batchAddTableRef.value?.acceptParams(params);
};
// 删除信息
const deleteInfo = async params => {
  await useHandleData(deleteMaterialType, { ids: [params.id] }, `删除【${params.category_name}】分类`);
  proTableRef.value?.getTableList();
};
// 批量删除信息
const batchDelete = async ids => {
  await useHandleData(deleteMaterialType, { ids }, '删除所选分类');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};

const changeDataScope = params => {
  switchLoading.value = true;
  const handleSuccess = resolve => {
    setTimeout(() => {
      switchLoading.value = false;
      proTableRef.value?.getTableList();
      ElMessage.success('修改状态成功');
      resolve(true);
    }, 200);
  };

  const handleError = reject => {
    setTimeout(() => {
      switchLoading.value = false;
      reject();
    }, 200);
  };

  return new Promise((resolve, reject) => {
    if (params.status === 1017001) {
      ElMessageBox.confirm(`您确认要禁用 [${params.category_name}] 类别吗? `, '温馨提示', {
        type: 'warning'
      })
        .then(() => {
          updateMaterialTypeStatus({ id: params.id, status: params.status })
            .then(() => handleSuccess(resolve))
            .catch(() => handleError(reject));
        })
        .catch(() => {
          switchLoading.value = false;
        });
    } else {
      updateMaterialTypeStatus({ id: params.id, status: params.status })
        .then(() => handleSuccess(resolve))
        .catch(() => handleError(reject));
    }
  });
};
</script>
